package translinkApp.Activities;

import java.io.InputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.util.EncodingUtils;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import translinkApp.Adaptors.JourneyToLocationAdapter;
import translinkApp.Data.Journey.Search.JourneySearch;
import translinkApp.Data.Journey.Search.JourneySearch.TimeType;
import translinkApp.Data.Journey.Search.JourneySearch.TransportType;
import translinkApp.Data.JourneyToLocation.JourneyToLocation;
import translinkApp.Data.JourneyToLocation.JourneyToLocationList;
import translinkApp.Data.Parse.KeyPair;
import translinkApp.Data.Parse.Journey.JourneysParse;
import translinkApp.Data.ResolvedLocation.ResolvedLocation;
import translinkApp.Data.Utils.Functions;
import translinkApp.Data.xmlparse.StationsHandler;
import translinkApp.views.TranslinkWebviewClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import com.lach.common.ErrorObject;
import com.lach.common.ProgressAsyncTask;

public class JourneyResultActivity extends Activity {

	private JourneySearch search;
	private WebView mWebView;
	private LinearLayout mWebTable;

	ArrayList<JourneyToLocationList> items;

	private static final String JOURNEY_SAVE = "journey";
	
	Handler h;

	/* An instance of this class will be registered as a JavaScript interface */
	class MyJavaScriptInterface {

		@SuppressWarnings("unused")
		public void processHTML(String html) {
			try {
				items = JourneysParse.getSearch(JourneyResultActivity.this, html);
				
				Message lmsg = new Message();
                lmsg.obj = "";
                lmsg.what = 0;
                JourneyResultActivity.this.h.sendMessage(lmsg);
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.web_view);
		Object journey = getIntent().getExtras().get(JOURNEY_SAVE);
		search = (JourneySearch) journey;

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		Boolean onlyTranslink = prefs.getBoolean("onlyTranslink", false);
		String priority = prefs.getString("priorityNew", "Timeliness");
		String walkMax = prefs.getString("maxwalk", "1000");
		String walkSpeed = prefs.getString("walkspeed", "Normal");

		mWebView = (WebView) findViewById(R.id.webView);
		mWebTable = (LinearLayout) findViewById(R.id.webAd);
		mWebView.setWebViewClient(new TranslinkWebviewClient());

		mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setSupportZoom(true);
		
//		this.h = new Handler() {
//
//            @Override
//            public void handleMessage(Message msg) {
//                // process incoming messages here
//                switch (msg.what) {
//                    case 0:
//                    	addOptionButtons();
//                    	break;
//                }
//                super.handleMessage(msg);
//            }
//        };		
		
		MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface();
		mWebView.addJavascriptInterface(myJavaScriptInterface, "HTMLOUT");

		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				/* Call whatever, It's finished loading. */
				mWebView.setVisibility(View.VISIBLE);
				//mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");

			}
		});

		if (savedInstanceState != null) {
			mWebView.restoreState(savedInstanceState);
		} else {

			String url = "http://mobile.jp.translink.com.au/travel-information/journey-planner";

			ArrayList<KeyPair> params = new ArrayList<KeyPair>();
			addLocationData(params, true, search.getFromLocation());
			addLocationData(params, false, search.getToLocation());

			if (search.getTimeType().equals(TimeType.ArriveBefore)) {
				params.add(new KeyPair("TimeSearchMode", "ArriveBefore"));

			} else if (search.getTimeType().equals(TimeType.LeaveAfter)) {
				params.add(new KeyPair("TimeSearchMode", "LeaveAfter"));

			} else if (search.getTimeType().equals(TimeType.FirstTrip)) {
				params.add(new KeyPair("TimeSearchMode", "FirstServices"));

			} else {
				params.add(new KeyPair("TimeSearchMode", "LastServices"));

			}
			params.add(new KeyPair("SearchDate", search.getDate().toString()));
			params.add(new KeyPair("SearchHour", new Integer(search.getTime().getHourMeridian())
					.toString()));
			params.add(new KeyPair("SearchMinute", new Integer(search.getTime().getMinute())
					.toString()));
			params.add(new KeyPair("TimeMeridiem", search.getTime().getAmPm().toString()));

			TransportType transType = search.getTransport();
			if ((transType == TransportType.All) || (transType == TransportType.Bus)) {
				params.add(new KeyPair("TransportModes", "Bus"));
			}
			if ((transType == TransportType.All) || (transType == TransportType.Train)) {
				params.add(new KeyPair("TransportModes", "Train"));
			}
			if ((transType == TransportType.All) || (transType == TransportType.Ferry)) {
				params.add(new KeyPair("TransportModes", "Ferry"));
			}
			params.add(new KeyPair("Priority", priority));
			params.add(new KeyPair("IncludeNonTranslinkServices", !onlyTranslink ? "true" : "false"));

			params.add(new KeyPair("MaximumWalkingDistance", walkMax));
			params.add(new KeyPair("WalkingSpeed", walkSpeed));

			String postData = "";

			for (int pair = 0; pair < params.size(); pair++) {
				postData += params.get(pair).getKey() + "=" + params.get(pair).getValue();

				if (pair < (params.size() - 1)) {
					postData += "&";
				}
			}

			mWebView.postUrl(url, EncodingUtils.getBytes(postData, "BASE64"));
		}

	}

//	public void addOptionButtons() {
//		LinearLayout row = (LinearLayout) findViewById(R.id.buttons);
//		for (int i = 0; i < items.size(); i++) {
//			Button b = new Button(this);
//			b.setText("Option " + (i + 1));
//			LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
//					LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
//			param.weight = (((float) items.size()) / ((float) i));
//			param.topMargin = 5;
//
//			final int selectedItem = i;
//
//			b.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//
//					JourneyToLocationAdapter adap = new JourneyToLocationAdapter(
//							JourneyResultActivity.this, items.get(selectedItem));
//
//					AlertDialog.Builder builder = new AlertDialog.Builder(
//							JourneyResultActivity.this);
//					builder.setTitle("Journey To Helper");
//
//					builder.setAdapter(adap, new DialogInterface.OnClickListener() {
//
//						public void onClick(DialogInterface dialog, int item) {
//							new LoadLocationFinder(JourneyResultActivity.this, items.get(selectedItem).get(
//									item)).execute();
//						}
//
//					});
//
//					AlertDialog alert = builder.create();
//					alert.show();
//
//				}
//
//			});
//			row.addView(b);
//		}
//		row.forceLayout();
//	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	protected void onSaveInstanceState(Bundle outState) {
		mWebView.saveState(outState);
	}

	private void addLocationData(ArrayList<KeyPair> params, boolean isFrom,
			ResolvedLocation location) {

		String locationType = ((isFrom) ? "From" : "To");
		String data = location.getLocationInformation();
		if (location.isStreet()) {
			String[] values = data.split(",");

			params.add(new KeyPair(locationType + "Street", values[0]));

			if (values.length > 1) {

				params.add(new KeyPair(locationType + "Suburb", values[1]));
			}
		} else {
			params.add(new KeyPair(locationType + "Suburb", data));
		}
	}
	

	private class LoadLocationFinder extends ProgressAsyncTask<JourneyToLocation> {

		private final JourneyToLocation location;

		public LoadLocationFinder(Context c, JourneyToLocation location) {
			super(c, "Please wait...", "Finding the GPS location");
			this.location = location;

		}

		protected ErrorObject<JourneyToLocation> doInBackground(String... params) {
			ErrorObject<JourneyToLocation> contacts = new ErrorObject<JourneyToLocation>();

			try {
				InputStream urlSource = Functions
						.getUrlStream("http://122.248.235.212:8080/TranslinkKiller-0.1/station/getStationByDescription?stationDescription="
								+ location.searchName);
				InputSource source = new InputSource(urlSource);
				SAXParserFactory factory = SAXParserFactory.newInstance();

				// create a parser
				SAXParser parser = factory.newSAXParser();

				// create the reader (scanner)
				XMLReader xmlreader = parser.getXMLReader();

				// instantiate our handler
				StationsHandler fh = new StationsHandler();

				// assign our handler
				xmlreader.setContentHandler(fh);

				// perform the synchronous parse
				xmlreader.parse(source);

				// should be done... let's display our results
				location.latitude = fh.getStations().get(0).latitude;
				location.longitude = fh.getStations().get(0).longitude;

				contacts.setItem(location);

			} catch (Exception e) {
				contacts.setException(e);
			}

			return contacts;

		}

		protected void onPostExecute(ErrorObject<JourneyToLocation> result) {
			super.onPostExecute(result);
			Intent intent;
			if (result.getItem() != null) {
				intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(String.format(
						"http://maps.google.com/maps?daddr=%s,%s", location.latitude,
						location.longitude)));
			} else {
				intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(String.format(
						"http://maps.google.com/maps?daddr=%s", location.displayName)));
			}
			intent.setClassName("com.google.android.apps.maps",
					"com.google.android.maps.MapsActivity");
			startActivity(intent);
		}
	}

}